package tool;

import java.io.File;
import java.net.PasswordAuthentication;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mengtian_tech.smart_lab.entity.apply.ApplyForm;

public class EmailTool {
	
	private static final String PASSWORD = "wangxudong";
	private static final String USER_NAME = "m13920160750@163.com";
	public static String ADMIN_RECEIVER = "endure75@gmail.com";
	public static String CLIENT_RECEIVER = "sales@endurego.com";
	private static Log log = LogFactory.getLog(EmailTool.class);
	
	public static void main(String args[]) throws Exception{
		File[] files = new File[]{new File("D:/Documents/Downloads/1.pdf")};
		sendFiles("您已经接受了报税申请的修改内容，具体内容请看附件","您已经接受了报税申请的修改内容，具体内容请看附件",files);
	}
	
	public static void sendAuditMsg(ApplyForm form,String host,String callbackURL)throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String title = "您有一个待审核的申请，请及时查看";		
		
		StringBuffer content = new StringBuffer();
		content.append("申请人姓名："+form.getApplyUser().getRealName());
		content.append("<br><br>");
		content.append("申请日期："+sdf.format(form.getApplyDate()));
		content.append("<br><br>");
		
		content.append("<a href='http://103.4.16.113");
		//content.append(host);
		content.append("/cwbz/loginController.do?login&callback=");
		content.append(callbackURL);
		content.append("'>");
		content.append("请点击此链接进入系统进行审核");
		content.append("</a>");
		log.info("发送邮件内容："+content.toString());
		sendMail(title, content.toString(),ADMIN_RECEIVER);
		
	}
	
	public static void sendDataChangeMsg(ApplyForm form,String host,String callbackURL) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String title = "您的申请已被修改，请及时查看进行确认";		
		
		StringBuffer content = new StringBuffer();
		content.append("申请人姓名："+form.getApplyUser().getRealName());
		content.append("<br><br>");
		content.append("申请日期："+sdf.format(form.getApplyDate()));
		content.append("<br><br>");
		
		content.append("<a href='http://103.4.16.113");
		//content.append(host);
		content.append("/cwbz/loginController.do?login&callback=");
		content.append(callbackURL);
		content.append("'>");
		content.append("请点击此链接进入系统进行修改确认");
		content.append("</a>");
		log.info("发送邮件内容："+content.toString());
		sendMail(title, content.toString(),CLIENT_RECEIVER);
	}
	
	
	private static void sendMail(final String title,final String content,final String rece) throws Exception{
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				try{
					Properties prop = getProps();	      
				     
				     //使用JavaMail发送邮件的5个步骤
				     //1、创建session
				     Session session = Session.getInstance(prop);	     
				     //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
				     session.setDebug(true);
				     
				     //2、通过session得到transport对象
				     Transport ts = session.getTransport();
				     
				     //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
				     ts.connect("smtp.163.com", USER_NAME, PASSWORD);
				     
				     //4、创建邮件
				     Message message = createSimpleMail(title,content,session,rece);
				     
				     //5、发送邮件
				     ts.sendMessage(message, message.getAllRecipients());
				     ts.close();
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		t.start(); 
	}
	
	 public static MimeMessage createSimpleMail(String title,String content,Session session,String rece)
	            throws Exception {
	        //创建邮件对象
	        MimeMessage message = new MimeMessage(session);
	        //指明邮件的发件人
	        message.setFrom(new InternetAddress(USER_NAME));
	        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
	        message.setRecipient(Message.RecipientType.TO, new InternetAddress(rece));
	        //邮件的标题
	        message.setSubject(title);
	        //邮件的文本内容
	        message.setContent(content, "text/html;charset=UTF-8");
	        //返回创建好的邮件对象
	        return message;
	 }
	 
	 public static void sendFiles(String title,String content,File[] files) throws Exception{
		 
		    Session session = Session.getDefaultInstance(getProps(), new MyAuthenticator(USER_NAME, PASSWORD));
		    session.setDebug(true);

		    //创建邮件对象
		    MimeMessage message = new MimeMessage(session);
		    // 邮件的标题
		    message.setSubject(title);
		    // 邮件发送日期
		    message.setSentDate(new Date());
		    // 指明邮件的发件人
		    message.setFrom(new InternetAddress(USER_NAME));

		    // 指明邮件的收件人
		    message.setRecipient(Message.RecipientType.TO, new InternetAddress(CLIENT_RECEIVER));

		    // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
		    Multipart multipart = new MimeMultipart();

		    // 添加邮件正文
		    BodyPart contentBodyPart = new MimeBodyPart();
		    // 邮件内容
		    contentBodyPart.setContent(content, "text/html;charset=UTF-8");
		    multipart.addBodyPart(contentBodyPart);


		    // 添加附件
		    for(File f : files){
		        BodyPart attachmentBodyPart = new MimeBodyPart();
		        // 根据附件路径获取文件,
		        FileDataSource dataSource = new FileDataSource(f);
			    attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
			    //MimeUtility.encodeWord可以避免文件名乱码
			    attachmentBodyPart.setFileName(MimeUtility.encodeWord(dataSource.getFile().getName()));
			    multipart.addBodyPart(attachmentBodyPart);
		    }
	 
		    // 邮件的文本内容
		    message.setContent(multipart);

		    // 4. 发送邮件,Transport每次发送成功程序帮忙关闭
		    Transport.send(message, message.getAllRecipients());
	 }

	private static Properties getProps() {
		Properties prop = new Properties();
		prop.setProperty("mail.host", "smtp.163.com");
		prop.setProperty("mail.transport.protocol", "smtp");
		prop.setProperty("mail.smtp.auth", "true");
		return prop;
	}
	
	static class MyAuthenticator extends Authenticator{
		private String username;
		private String password;
		public MyAuthenticator(String u,String p){
			this.username = u;
			this.password = p;
		}
		
		protected javax.mail.PasswordAuthentication getPasswordAuthentication(){
			return new javax.mail.PasswordAuthentication(username,password);
		}
	}
}
